package mi.payment.transaction;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.RemoteException;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import lainey.ui.dialog.IconHintDialog;
import lainey.ui.utils.LogUtil;
import lainey.ui.widget.TitleView;
import mi.payment.BuildConfig;
import mi.payment.R;
import mi.payment.constants.BaseErrorCode;
import mi.payment.constants.Configs;
import mi.payment.constants.Params;
import mi.payment.db.dao.PayDetail;
import mi.payment.settings.MerchantSettingsOperation;
import mi.payment.settings.SalesSlipPrintSettings;
import mi.payment.settings.SalesSlipPrintSettingsOperation;
import mi.payment.ui.print.BasePrintCallback;
import mi.payment.ui.print.helper.BasePrintController;
import mi.payment.ui.print.helper.PrintController;
import mi.payment.utils.SNUtils;
import mi.payment.utils.SettingHomePageUtils;
import mi.payment.utils.UIUtils;
import mi.payment.utils.datacollection.PayDetailCollection;
import mi.payment.utils.print.DataPrinterKernel;
import sunmi.payment.L3.L3BroadcastHelper;
import woyou.aidlservice.jiuiv5.ICallback;

public class ResultActivity extends AutoFinishActivity {

    private ImageView mIvState;
    private TextView mTvState;
    private TextView mTvResult;
    private TextView mTvInfo;
    private Button mBtnOK;

    private boolean isSuccess;
    private PayDetail mPayDetail;

    // 页面自动关闭时倒计数次数
    private boolean isShowDialog;
    private int mCountDownTime = 5;

    // 最大打印张数
    private int mReceiptSingleNum;
    private int mCurrentPrintNum = 2;

    private IconHintDialog mIconHintDialog;
    private BasePrintController mController;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.transaction_activity_result);
        initView();
        fullData();
        if (isSuccess) {
            isNeedPrinterTwoLines();
        }
    }

    private void isNeedPrinterTwoLines() {
        SalesSlipPrintSettings salesSlipPrintSettings = SalesSlipPrintSettingsOperation.getInstance().getSalesSlipPrintSettings();
        boolean isScanCodePrint = salesSlipPrintSettings.isScanCodePrint();     // 扫码类交易打印凭条
        String singleNum = salesSlipPrintSettings.getPrintReceiptSingleNum();   // 打印凭条单联数
        int scanCodeSalesSlip = salesSlipPrintSettings.getScanCodeSalesSlip();  // 扫码类签购单设置  1.仅打印商户联   2.打印商户联与用户联
        LogUtil.e(Configs.TAG, "打印凭条单联数:" + singleNum);
        LogUtil.e(Configs.TAG, "扫码类交易打印凭条:" + isScanCodePrint);
        LogUtil.e(Configs.TAG, "扫码类签购单设置:" + scanCodeSalesSlip);
        try {
            mReceiptSingleNum = Integer.parseInt(singleNum);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (Params.sL3Params == null || Params.sL3Params.isPrintTicket) {
            showPrintTicketDialog();
        } else {
            // 如果外调程序不打印小票的话
            startCountDown();
        }
    }

    private void initView() {
        Intent intent = getIntent();
        int iconResId = intent.getIntExtra("extra_icon", 0);
        int titleResId = intent.getIntExtra("extra_title", 0);
        String resultStr = intent.getStringExtra("extra_result");
        mPayDetail = (PayDetail) intent.getSerializableExtra("extra_payDetail");

        TitleView titleView = findViewById(R.id.title_view);
        titleView.setLeftImageVisibility(View.GONE);
        titleView.setCenterText(titleResId);

        mIvState = findViewById(R.id.iv_state);
        mTvState = findViewById(R.id.tv_state);
        mTvResult = findViewById(R.id.tv_result);
        mTvInfo = findViewById(R.id.tv_info);
        mBtnOK = findViewById(R.id.mb_ok);
        mBtnOK.setOnClickListener(
                v -> onBackPressed()
        );
    }

    private void fullData() {
        if (mPayDetail == null) return;
        mController = new PrintController(this);

        // 增加消费笔数
        SettingHomePageUtils.getInstance().addConsume(mPayDetail.transType);
        // 上送数据给dataService
        PayDetail dataServicePayDetail = mPayDetail;    // payDetail中isPrinted字段不会更新（只会在数据库中更新），需要重新判断
        dataServicePayDetail.setIsPrinted(isSuccess);   // 判断是否已经打印
        PayDetailCollection.getInstance().uploadData(dataServicePayDetail);

        String resultDes = mPayDetail.getTradeResultDes();
        String answerCode = mPayDetail.getTradeAnswerCode();

        // 判断交易是否成功
        boolean equals = TextUtils.equals("00", answerCode);
        if (mPayDetail.transPlatform == 0) {
            isSuccess = equals;
        } else {
            isSuccess = equals && mPayDetail.QRCodeTransState == 1;
        }

        String hintText = getString(R.string.index_version) + BuildConfig.VERSION_NAME + "\n";
        hintText += getString(R.string.index_sn) + SNUtils.getBindSN() + "\n";
        hintText += getString(R.string.index_terminal) + MerchantSettingsOperation.getInstance().getMerManagerSettings().getTerminalNum() + "\n";
        if (isSuccess) {
            mIvState.setImageResource(R.drawable.state_print_success);
            mTvState.setText(R.string.index_state_success);
            mTvResult.setText(R.string.index_print_success);
            mTvInfo.setText(hintText);
        } else {
            mIvState.setImageResource(R.drawable.state_print_failed);
            mTvState.setText(R.string.index_state_fail);
            if (mPayDetail.transPlatform != 0 && mPayDetail.QRCodeTransState == 2) {
                // 二维码支付中
                mTvState.setText(R.string.index_state_paying);
                mTvResult.setText(R.string.index_result_message);
                mTvInfo.setText(R.string.index_result_hint);
            } else {
                String code = BaseErrorCode.getCode(answerCode, resultDes);
                mTvResult.setText(code);
                mTvInfo.setText(hintText);
            }
        }
    }

    @Override
    public void onBackPressed() {
        if (Params.sL3Params != null) {
            sendCloseAppBroadcast();
            L3BroadcastHelper.sendResultBroadcast(mContext, isSuccess, mPayDetail);
        } else {
            sendCloseActivityBroadcast();
        }
        super.onBackPressed();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (Params.sL3Params == null) {
            UIUtils.screenMonopoly(-1);
        }
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
        }
        dismissPrintTicketDialog();
    }

    private void startCountDown() {
        mCountDownTime = 5;
        refreshButton();
        if (mHandler != null) {
            mHandler.sendEmptyMessageDelayed(0, 1000);
        }
    }

    private void refreshButton() {
        if (isShowDialog) {
            String hint = String.format("%s(%s)", getString(R.string.ok), mCountDownTime);
            if (mIconHintDialog != null) {
                mIconHintDialog.setRightText(hint);
            }
            mBtnOK.setText(R.string.index_back);
        } else if (mCountDownTime == 0) {
            mBtnOK.setText(R.string.index_back);
        } else {
            String hint = String.format("%s(%s)", getString(R.string.index_back), mCountDownTime);
            mBtnOK.setText(hint);
        }
    }

    private void startPrint() {
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
        }
        dismissPrintTicketDialog();
        try {
            int printStatus = DataPrinterKernel.INSTANCE().updatePrinterState();
            if (printStatus == 1) {
                mTvResult.setText(R.string.index_print_ing);
                mIvState.setBackgroundResource(R.drawable.state_print);
                mController.print(mPayDetail, mPrintCallback, mCurrentPrintNum, false);
            } else {
                showToast(R.string.error_printer);
                handlePrintException();
            }
        } catch (Exception e) {
            showToast(R.string.error_printer);
            handlePrintException();
        }
    }

    private void handlePrintException() {
        mTvResult.setText(R.string.index_print_fail);
        mIvState.setBackgroundResource(R.drawable.state_print_failed);
        isShowDialog = false;
        startCountDown();
    }

    private ICallback mPrintCallback = new BasePrintCallback() {

        @Override
        public void onPrintResult(int code, String msg) throws RemoteException {
            runOnUI(
                    () -> {
                        if (code == 0) {
                            mTvResult.setText(R.string.index_print_keep_ticket);
                            mIvState.setBackgroundResource(R.drawable.state_print_success);
                            if (mCurrentPrintNum < mReceiptSingleNum) {
                                mCurrentPrintNum++;
                                showPrintTicketDialog();
                            } else {
                                isShowDialog = false;
                                startCountDown();
                            }
                        } else {
                            LogUtil.e(Configs.TAG, "打印失败 code:" + code + " msg:" + msg);
                            mTvResult.setText(R.string.index_print_fail);
                            mIvState.setBackgroundResource(R.drawable.state_print_failed);
                        }
                    }
            );
        }

    };

    @SuppressWarnings("HandlerLeak")
    private Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            if (mCountDownTime == 0) {
                if (isShowDialog) {
                    startPrint();
                } else {
                    onBackPressed();
                }
            } else {
                refreshButton();
                mCountDownTime--;
                sendEmptyMessageDelayed(0, 1000);
            }
        }

    };

    private void showPrintTicketDialog() {
        if (mIconHintDialog == null) {
            mIconHintDialog = new IconHintDialog(this);
            mIconHintDialog.setRightText(R.string.ok);
            mIconHintDialog.setLeftText(R.string.cancel);
            mIconHintDialog.setIconResource(R.drawable.state_warning);
            mIconHintDialog.setMessage(R.string.index_print_next_joint);
            mIconHintDialog.setCancelable(false);
            mIconHintDialog.setCanceledOnTouchOutside(false);
            mIconHintDialog.setLeftOnClickListener(
                    v -> onBackPressed()
            );
            mIconHintDialog.setRightOnClickListener(
                    v -> startPrint()
            );
        }
        try {
            isShowDialog = true;
            mIconHintDialog.show();
            startCountDown();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void dismissPrintTicketDialog() {
        if (mIconHintDialog != null) {
            try {
                mIconHintDialog.dismiss();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static void startAction(Context context, int titleResId, PayDetail payDetail) {
        startAction(context, titleResId, 0, "", payDetail);
    }

    public static void startAction(Context context, int titleResId, String result, PayDetail payDetail) {
        startAction(context, titleResId, 0, result, payDetail);
    }

    public static void startAction(Context context, int titleResId, int iconResId, String result, PayDetail payDetail) {
        Intent intent = new Intent(context, ResultActivity.class);
        intent.putExtra("extra_title", titleResId);
        intent.putExtra("extra_icon", iconResId);
        intent.putExtra("extra_result", result);
        intent.putExtra("extra_payDetail", payDetail);
        context.startActivity(intent);
    }


}
